@extends('layouts.default')
@section('css')
    <link rel="stylesheet" href="{{asset('admin-lte/plugins/datatables/dataTables.bootstrap4.css')}}">
    <style>
        #mymodal tbody {
            display: block;
            height: 500px;
            overflow-y: scroll;
        }

        #mymodal table thead,
        #mymodal tbody tr {
            display: table;
            width: 100%;
            table-layout: fixed;
        }

        #mymodal table thead {
            width: calc( 100% - 1em)
        }
        #mymodal tbody input{
            width:100%;
        }
        #mymodal tbody td{
            text-align: center;
        }

        /*table thead th {*/
            /*background: #ccc;*/
        /*}*/

    </style>
@stop

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">商品管理 / <a class="text-primary" href="{{url('admin/spu/index')}}">商品列表</a></h3>
                </div>

                <div class="card-body">
                    @include('layouts.message')
                    <button class="btn btn-info btn-sm" style="margin-bottom:10px" onclick="location.href='{{url('admin/spu/create')}}'">添加商品</button>
                    <button data-url="{{url('admin/spu/market')}}" data-markertable=1 class="btn btn-success btn-sm batch-market" style="margin-bottom:10px" >批量上架</button>
                    <button data-url="{{url('admin/spu/market')}}" data-markertable=0 class="batch-market btn btn-warning btn-sm" style="margin-bottom:10px" >批量下架</button>
                    <table id="example1" class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th><input type="checkbox" class="selAll"></th>
                            <th>操作</th>
                            <th>上级组织</th>
                            <th>商品图片</th>
                            <th>名称</th>
                            {{--<th>所属分类</th>--}}
                            <th>原价</th>
                            <th>现价</th>
                            <th>库存</th>
                            <th>上架状态</th>
                            <th>排序序号</th>
                        </tr>
                        </thead>
                        <tbody>
                            <tr>
                                {{--<td><input type="checkbox" value="{{ $list['goods_id'] }}" name="sel_spu_id" class="sel-spu"></td>--}}
                                {{--<td>--}}
                                    {{--<button class="btn btn-sm btn-primary" onclick="location.href='{{url('admin/spu/edit',['spu_id'=>$list['goods_id']])}}'">编辑</button>--}}
                                    {{--<button data-url="{{url('admin/spu/del',['spu_id'=>$list['goods_id']])}}" class="btn btn-sm btn-danger del-goods">删除</button>--}}
                                {{--</td>--}}
                                {{--<td>{{ $list['goods_id'] }}</td>--}}
                                {{--<td><img style="max-width: 6vw;" src="{{ $list['image'] }}" alt=""></td>--}}
                                {{--<td>{{ $list['goods_name'] }}</td>--}}
                                {{--<td>{{ $list['cate_name'] }}</td>--}}
                                {{--<td>{{ $list['price'] }}</td>--}}
                                {{--<td>{{ $list['discount_price'] }}</td>--}}
                                {{--<td>{{ $list['stock'] }}</td>--}}
                                {{--<td>{{ $list['marketable'] == 0 ? '未上架' :'已上架'}}</td>--}}
                                {{--<td>{{ $list['sort'] }}</td>--}}
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="10"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                {{--关联商品的模态框--}}
                @include('admin.spu.stock_modal')
            </div>
        </div>
    </div>


@stop
@section('script')
    <script src="{{asset('admin-lte/plugins/datatables/jquery.dataTables.js')}}"></script>
    <script src="{{asset('admin-lte/plugins/datatables/dataTables.bootstrap4.js')}}"></script>
    <script>
        var spuedit_url = '{{$spuedit_url}}',
            spudel_url = '{{$spuedel_url}}',
            spulist_url = '{{$spulist_url}}',
            hotelgoods_url = '{{url('api/hotel/hotel_goods_list')}}',
            update_hotelstock = '{{url('api/hotel/update_stock')}}';
        $(function () {
            $("#example1").DataTable({
                 "language"  : {
                     url :'https://cdn.datatables.net/plug-ins/1.10.19/i18n/Chinese.json'
                 },
                //启用或者禁用某一列的排序功能
                "columnDefs": [
                    { "orderable": false, "targets": 0 }
                 ],
                "processing": true,
                "serverSide": true,
                 ajax : spulist_url,
                "deferRender": true,
                columns: [
                        {
                            "data": function(row,type,val,meta){
                                        return '<input type="checkbox" value="'+row.goods_id+'" name="sel_spu_id" class="sel-spu">';
                                    },
                            orderable :false,
                            searchable:false,
                        },
                        {
                            "data": function(row,type,val,meta){
                                return '' +
                                    '<button class="btn btn-sm btn-primary edit-goods" ' +
                                    'data-url="'+spuedit_url+'/'+row.goods_id+'"">编辑</button>&nbsp;' +'<button data-url="'+spudel_url+'/'+row.goods_id+'"" class="btn btn-sm btn-danger del-goods">删除</button>&nbsp;'+'<button class="btn btn-sm btn-info assign_stock" data-goods_id="'+row.goods_id+'">分配酒店库存</button>';
                            },
                            orderable:false,
                        },
                        { "data": "goods_id" },
                        {
                            "data": function(row,type,val,meta){
                                return '<img style="max-width: 6vw;" src="'+row.image+'">';
                            },
                            orderable:false,
                        },
                        { "data": "goods_name" },
                        // { "data": "cate_name" },
                        { "data": "price" },
                        { "data": "discount_price" },
                        { "data": "stock"},
                        { "data": "market_status",'searchable':false},
                        { "data": "sort",'searchable':false},
                 ],
                buttons: [
                    {
                        text: 'Alert',
                        action: function ( e, dt, node, config ) {
                            alert( 'Activated!' );
                            this.disable(); // disable button
                        }
                    }
                ]
            });

        });
        $('#example1').on('click','.del-goods',function(e){
            layer.confirm('确认要删除该商品吗？',function(){
                location.href = $(e.target).data('url');
            })
        })
            .on('click','.edit-goods',function(e){
                location.href = $(e.target).data('url');
            });

        //批量上下架操作
        $('.batch-market').on('click',function(e){
            var target = $(e.target),
                marketable = target.data('markertable'),
                markertable_msg = marketable==0?'下架':'上架',
                url = target.data('url'),
                sel_spu_id = [];
            $.each($('input[name="sel_spu_id"]:checked'),function(k,v){
                sel_spu_id.push($(v).val());
            });

            if(sel_spu_id.length === 0){
                layer.alert('请选择你要'+markertable_msg+'的商品');
                return false;
            }
            layer.confirm('你确定要'+markertable_msg+'选中的这些商品吗?',function(){
                sel_spu_id = sel_spu_id.join(',');
                location.href = url + '/' + sel_spu_id + '/' + marketable;
            })

        })

        //全选反选
        $('.selAll').click(function(e){
            $.each($('tbody input[type="checkbox"]'),function(k,v){
                $(v).prop('checked',$(e.target).prop('checked'));
            })
        });

        console.log(parseInt(-1)+10);


        var goods = {
            goods_id : '',//点击分配库存的商品id
            total_stock:0,
            setting_stock : 0,
            form_valid : true,
            init : function(){
                this.bindEvents();
            },
            bindEvents:function(){
                var that = this;
                //点击分配库存按钮触发的事件
                $('.card-body').on('click','.assign_stock',function(e){
                    var $assign_button = $(this);
                    that.goods_id = $assign_button.data('goods_id');
                    that.api_hotel_stock_list();
                })
                $('.card').on('blur','.update_stock',function () {
                    // alert('blur');
                    that.blurInput($(this));
                });
                $('.relate_goods').on('click',function(e){
                    that.grid_key = $(this).parent().data('grid');
                    that.getGoodsList();
                });

                // $('#mymodal').on('click','.pagination a',function(e){
                //     e.preventDefault();
                // var href = $(this).attr('href');
                // $.ajax({
                //     url : href,
                //     success:function(data){
                //         var $html = that.renderTbody(data);
                //         $('#mymodal tbody').html($html);
                //         $('#pagecontainer').html(data.pages);
                //     },
                // })
                // });
                $('.modal-confirm').on("click",function(e){
                    if(!that.form_valid){
                       return false;
                    }
                    that.api_update_stock();
                })
            },

            //指定商品的酒店库存列表
            api_hotel_stock_list(){
                var that = this;
                $.ajax({
                    type : 'POST',
                    url  : hotelgoods_url,
                    data : {'goods_id':this.goods_id},
                    success:function(res){
                        $('.assigned_stock').html(0);
                        that.setting_stock = 0;
                        that.form_valid = true;
                        if(res.ret == 200){
                            that.renderHotelGoodsList(res.data);
                        }
                        $('#mymodal').modal();
                    }
                })
            },

            //渲染酒店商品列表
            renderHotelGoodsList(data){
                var template_html = '';
                var total_stock = 0;
                var that = this;
                $.each(data,function(k,v){
                    that.total_stock = v.total_stock;
                    total_stock = v.total_stock;
                    template_html += ' <tr data-total_stock="'+v.total_stock+'" data-goods_id="'+v.goods_id+'" data-hotel_id="'+v.hotel_id+'">\n' +
                        '                            <td>'+(k+1)+'</td>\n' +
                        '                            <td>'+v.hotel_name+'</td>\n' +
                        '                            <td>'+v.goods_name+'</td>\n' +
                        '                            <td><img style="width:100px" src="'+v.image+'" alt=""></td>\n' +
                        '                            <td>'+v.hotel_stock+'</td>\n' +
                        '                            <td><input type="number" class="update_stock" type="text" name="update_stock" value="0"></td>\n' +
                        '                            <td><input type="text" disabled="true" value="'+v.hotel_stock+'"></td>\n' +
                        '                        </tr>';
                });
                $('#mymodal tbody').html(template_html);
                $('#mymodal .total_stock').html(total_stock);
            },

            //检查输入的库存是否符合要求，并给出提示
            checkStockInput(){
                var that = this;
                var setting_total_stock = 0;
                $flag = true;
                //遍历检查库存设置是否符合要求
                $.each($('#mymodal .update_stock'),function(k,v){
                   var $tr_data = that.getTdsRow($(this)),
                        hotel_name = $tr_data.hotel_name,
                        update_stock = $tr_data.update_stock,
                        hotel_stock = $tr_data.hotel_stock,
                        total_stock = parseInt(that.total_stock);

                    //检查是否是合法的数字
                    // if()

                    //首先检查该酒店设置的库存是否超出总库存
                    if($(this).val() > total_stock ){
                        layer.msg(hotel_name+'的库存超出总库存!');
                        $flag = false;
                        return false;
                    }

                    //其次检查该酒店设置的库存是否小于该酒店原有的库存
                    if(hotel_stock + update_stock < 0){
                        layer.msg(hotel_name+'设置的库存小于了该酒店现有库存!');
                        $flag = false;
                        return false;
                    }

                    //检查设置的所有酒店的累加库存是否超出了该商品的总库存
                    setting_total_stock += update_stock;
                    if(setting_total_stock > that.total_stock){
                        layer.msg('分配的总库存数超出该商品的总库存');
                        $flag = false;
                        return false;
                    }
                    that.setting_stock = setting_total_stock;
                });
                return $flag;
            },

            //输入框失去焦点之后的事件
            blurInput($input){
                var $tr_data = this.getTdsRow($input);
                if(!this.checkStockInput()){
                    //不符合要求重置为0
                    // $input.val(0);
                    // $tr_data.$_td.eq(6).find('input').val($tr_data.hotel_stock);
                    this.form_valid = false;
                    return false;
                }
                this.form_valid = true;

                //符合要求的将变更后库存更新
                $tr_data.$_td.eq(6).find('input').val($tr_data.hotel_stock+$tr_data.update_stock);

                //已分配库存更新
                $('.assigned_stock').html(this.setting_stock);

                return true;
            },

            getTdsRow($input){
                $tds = $input.parent().parent().find('td');
                var update_stock = 0;
                if($tds.eq(5).find('input').val()){
                    update_stock =  parseInt($tds.eq(5).find('input').val());
                }else{
                    $input.val(0);
                }
                return {
                    hotel_stock : parseInt($tds.eq(4).html()),
                    hotel_name  : $tds.eq(1).html(),
                    goods_name  : $tds.eq(2).html(),
                    update_stock : update_stock,
                    $_td : $tds,
                    hotel_id : $tds.eq(0).parent().data('hotel_id'),
                    goods_id : $tds.eq(0).parent().data('goods_id'),
                }
            },

            //调用api更新库存
            api_update_stock(){
                var index = layer.load(1, {
                    shade: [0.7,'#fff'] //0.1透明度的白色背景
                });
                var postData = [];
                var that = this;

                //组合出提交的数据
                $.each($('.update_stock'),function(k,v){
                    var $tr_data = that.getTdsRow($(this));
                    postData.push({
                        hotel_id : $tr_data.hotel_id,
                        goods_id : $tr_data.goods_id,
                        update_stock : $tr_data.update_stock,
                    })
                });

                console.log(postData);

                $.ajax({
                    url : update_hotelstock,
                    data : {data:postData},
                    type : 'POST',
                    success:function(res){
                      layer.close(index);
                      $('#mymodal').modal('hide');
                    },
                })
            },
        }

        goods.init();

    </script>
@stop